package com.gmcc.docmanager.db;

import com.gmcc.docmanager.entity.Account;
import com.gmcc.docmanager.util.Utils;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

public class AccountDao {

	public static void saveAccount(Context context, Account account) {
		if (account == null || TextUtils.isEmpty(account.getName())
				|| TextUtils.isEmpty(account.getPassword())) {
			return;
		}
		deleteAllAccounts(context);
		createAccount(context, account.getName(), account.getPassword());
	}

	public static Account getAccount(Context context) {
		Cursor cursor = null;
		Account account = null;
		DatabaseHelper dbHelper = new DatabaseHelper(context);
		try {
			SQLiteDatabase db = dbHelper.getWritableDatabase();
			cursor = db.query(DatabaseHelper.DATABASE_TABLE_ACCOUNT,
					new String[] { DatabaseHelper.FIELD_ACCOUNT_NAME,
							DatabaseHelper.FIELD_ACCOUNT_PASSWORD }, null,
					null, null, null, null);
			if (cursor != null && cursor.moveToNext()) {
				account = new Account();
				account.setName(cursor.getString(cursor
						.getColumnIndex(DatabaseHelper.FIELD_ACCOUNT_NAME)));
				account.setPassword(Utils.bs(cursor.getString(cursor
						.getColumnIndex(DatabaseHelper.FIELD_ACCOUNT_PASSWORD))));
			}
		} finally {
			if (cursor != null) {
				cursor.close();
			}
			dbHelper.close();
		}
		return account;
	}

	private static long createAccount(Context context, String name,
			String password) {
		DatabaseHelper dbHelper = new DatabaseHelper(context);
		try {
			SQLiteDatabase db = dbHelper.getWritableDatabase();
			ContentValues initialValues = new ContentValues();
			initialValues.put(DatabaseHelper.FIELD_ACCOUNT_NAME, name);
			initialValues.put(DatabaseHelper.FIELD_ACCOUNT_PASSWORD,
					Utils.as(password));
			return db.insert(DatabaseHelper.DATABASE_TABLE_ACCOUNT, null,
					initialValues);
		} finally {
			dbHelper.close();
		}
	}

	public static void deleteAllAccounts(Context context) {
		DatabaseHelper dbHelper = new DatabaseHelper(context);
		try {
			SQLiteDatabase db = dbHelper.getWritableDatabase();
			db.delete(DatabaseHelper.DATABASE_TABLE_ACCOUNT, null, null);
		} finally {
			dbHelper.close();
		}
	}

}
